package cn.com.acca.ma.thread.picture;

import static cn.com.acca.ma.thread.AbstractThread.BULL_RANGE_SHORT_ORDER_PROPERTIES;

import cn.com.acca.ma.globalvariable.WechatSubscriptionGlobalVariable;
import cn.com.acca.ma.service.StockTransactionDataService;
import cn.com.acca.ma.thread.AbstractThread;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.xmlbeans.XmlCursor;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 创建股票收盘价图
 */
public class CreateClosePictureThread extends AbstractThread implements Runnable {

    private static Logger logger = LogManager.getLogger(CreateClosePictureThread.class);

    private StockTransactionDataService stockTransactionDataService;

    public CreateClosePictureThread() {
    }

    public CreateClosePictureThread(StockTransactionDataService stockTransactionDataService) {
        this.stockTransactionDataService = stockTransactionDataService;
    }

    @Override
    public void run() {
        logger.info("启动线程，开始生成股票收盘价图，调用的方法为【createClosePicture】");

        stockTransactionDataService.createClosePicture(Boolean.TRUE, Boolean.TRUE);

        synchronized (AbstractThread.class){
            WechatSubscriptionGlobalVariable.wechatSubscriptionThreadFinishNumber++;
            logger.info("已经完成了【" + WechatSubscriptionGlobalVariable.wechatSubscriptionThreadFinishNumber + "】个线程");
            generateSubReport();
        }
    }

    /**
     * 创建子报告
     */
    @Override
    public void generateSubReport() {
        String subReportFile = "/mywork/gitcode-repository/hades/liangu/文章/使用说明/output/多空排列图/多空排列图.docx";

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(subReportFile));
            XWPFDocument xwpfDocument= new XWPFDocument();

            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new File(AbstractThread.BULL_RANGE_SHORT_ORDER_PROPERTIES));
            Element paragraphListElement = document.getRootElement();

            // 段落间距
            Integer paragraphSpacingAfter = Integer.parseInt(paragraphListElement.attribute("paragraphSpacingAfter").getValue());
            Integer paragraphSpacingBefore = Integer.parseInt(paragraphListElement.attribute("paragraphSpacingBefore").getValue());

            Iterator paragraphIterator = paragraphListElement.elementIterator();
            while (paragraphIterator.hasNext()) {
                Element paragraphElement = (Element) paragraphIterator.next();
                if (paragraphElement.getName().equals("paragraph")) {
                    Iterator iterator = paragraphElement.elementIterator();
                    Element element = (Element) iterator.next();
                    // text标签
                    if (element.getName().equals("text")){
                        String font = element.attribute("font").getValue();
                        String color = element.attribute("color").getValue();
                        Integer size = Integer.parseInt(element.attribute("size").getValue());
                        Boolean bold = Boolean.parseBoolean(element.attribute("bold").getValue());
                        String text = element.getText().trim();

                        // 段落间距
                        XWPFParagraph xwpfParagraph = xwpfDocument.createParagraph();
                        xwpfParagraph.setAlignment(ParagraphAlignment.LEFT);
                        xwpfParagraph.setSpacingAfter(paragraphSpacingAfter);
                        xwpfParagraph.setSpacingBefore(paragraphSpacingBefore);

                        XWPFRun xwpfRun = xwpfParagraph.createRun();
                        xwpfRun.setColor(color);
                        xwpfRun.setFontSize(size);
                        xwpfRun.setFontFamily(font);
                        xwpfRun.setBold(bold);
                        xwpfRun.setText(text);
                    }
                    // image标签
                    if (element.getName().equals("image")){
                        Integer width = Integer.parseInt(element.attribute("width").getValue());
                        Integer height = Integer.parseInt(element.attribute("height").getValue());
                        String imageFile = element.getText().trim();

                        XWPFParagraph xwpfParagraph = xwpfDocument.createParagraph();
                        // 段落间距
                        xwpfParagraph.setSpacingAfter(paragraphSpacingAfter);
                        xwpfParagraph.setSpacingBefore(paragraphSpacingBefore);
                        XmlCursor xmlCursor = xwpfParagraph.getCTP().newCursor();
                        XWPFParagraph newXwpfParagraph = xwpfDocument.insertNewParagraph(xmlCursor);
                        newXwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
                        XWPFRun newParaRun = newXwpfParagraph.createRun();
                        newParaRun.addPicture(new FileInputStream(imageFile), XWPFDocument.PICTURE_TYPE_PNG,null, Units.toEMU(width), Units.toEMU(height));
                        xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));
                    }
                }
            }

            xwpfDocument.write(fileOutputStream);
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        logger.info("报告【" + subReportFile + "】创建完成");
    }
}
